<template>
  <el-dialog
    v-model="visible"
    title="库存详情"
    width="800px"
    :before-close="handleClose"
    class="inventory-detail-dialog"
  >
    <div class="inventory-detail" v-if="item">
      <el-tabs v-model="activeTab" class="detail-tabs">
        <el-tab-pane label="基本信息" name="basic" class="tab-pane">
          <el-descriptions :column="2" border class="detail-descriptions">
            <el-descriptions-item label="产品名称" :span="2">
              {{ item.productName }}
            </el-descriptions-item>
            <el-descriptions-item label="SKU">
              {{ item.sku }}
            </el-descriptions-item>
            <el-descriptions-item label="产品规格">
              {{ item.specification }}
            </el-descriptions-item>
            <el-descriptions-item label="当前库存">
              <el-tag :type="getStockStatusType(item.status)" class="status-tag">
                {{ item.currentStock }} {{ item.unit }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="库存状态">
              <el-tag :type="getStockStatusType(item.status)" class="status-tag">
                {{ getStockStatusText(item.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="最低库存">
              {{ item.minStock }} {{ item.unit }}
            </el-descriptions-item>
            <el-descriptions-item label="最高库存">
              {{ item.maxStock }} {{ item.unit }}
            </el-descriptions-item>
            <el-descriptions-item label="最后更新">
              {{ formatDate(item.lastUpdate) }}
            </el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">
              {{ item.remark || '无' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        
        <el-tab-pane label="库存记录" name="records" class="tab-pane">
          <el-table :data="inventoryRecords" v-loading="loadingRecords" style="width: 100%" class="records-table">
            <el-table-column prop="date" label="操作时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.date) }}
              </template>
            </el-table-column>
            <el-table-column prop="type" label="操作类型" width="120">
              <template #default="scope">
                <el-tag :type="getRecordType(scope.row.type)" class="record-type-tag">
                  {{ getRecordTypeText(scope.row.type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="数量变化" width="120">
              <template #default="scope">
                <span :class="getAmountClass(scope.row.amount)">
                  {{ scope.row.amount > 0 ? '+' : '' }}{{ scope.row.amount }} {{ item.unit }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="balance" label="操作后余额" width="120" />
            <el-table-column prop="reason" label="操作原因" width="150" />
            <el-table-column prop="operator" label="操作人" width="120" />
            <el-table-column prop="remark" label="备注" />
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="recordPagination.page"
              v-model:page-size="recordPagination.limit"
              :total="recordPagination.total"
              :page-sizes="[10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="库存预警" name="alerts" class="tab-pane">
          <el-alert
            title="库存预警设置"
            type="info"
            show-icon
            :closable="false"
            class="alert-info"
          />
          
          <el-form :model="alertForm" label-width="120px" class="alert-form">
            <el-form-item label="预警方式">
              <el-checkbox-group v-model="alertForm.alertMethods" class="checkbox-group">
                <el-checkbox value="email" class="checkbox-item">邮件通知</el-checkbox>
                <el-checkbox value="sms" class="checkbox-item">短信通知</el-checkbox>
                <el-checkbox value="system" class="checkbox-item">系统消息</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            
            <el-form-item label="预警阈值">
              <el-input-number 
                v-model="alertForm.threshold" 
                :min="0" 
                :max="item.maxStock"
                controls-position="right"
                style="width: 120px"
                class="threshold-input"
              />
              <span class="unit">{{ item.unit }}</span>
            </el-form-item>
            
            <el-form-item label="预警频率">
              <el-select v-model="alertForm.frequency" style="width: 200px" class="frequency-select">
                <el-option label="实时预警" value="realtime" />
                <el-option label="每日汇总" value="daily" />
                <el-option label="每周汇总" value="weekly" />
              </el-select>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveAlertSettings" class="save-alert-btn">
                保存预警设置
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
// @ts-nocheck
import { ref, computed, defineProps, defineEmits, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as inventoryAPI from '@/api/inventory'

interface InventoryItem {
  id: number
  productId: number
  sku: string
  productName: string
  specification: string
  currentStock: number
  minStock: number
  maxStock: number
  unit: string
  lastUpdate: string
  status: string
  remark: string
}

interface InventoryRecord {
  id: number
  date: string
  type: string
  amount: number
  balance: number
  reason: string
  operator: string
  remark: string
}

interface AlertForm {
  alertMethods: string[]
  threshold: number
  frequency: string
}

const props = defineProps<{
  modelValue: boolean
  item: InventoryItem | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'close'): void
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit('update:modelValue', value)
})

const activeTab = ref('basic')
const loadingRecords = ref(false)

const inventoryRecords = ref<InventoryRecord[]>([])

const recordPagination = ref({
  page: 1,
  limit: 10,
  total: 0
})

const alertForm = ref<AlertForm>({
  alertMethods: ['email', 'system'],
  threshold: 5,
  frequency: 'realtime'
})

// 监听item变化，初始化预警设置
watch(() => props.item, (newVal: InventoryItem | null) => {
  if (newVal) {
    alertForm.value.threshold = newVal.minStock
    // 加载库存记录
    if (activeTab.value === 'records') {
      loadInventoryRecords()
    }
  }
}, { immediate: true })

// 监听tab变化，当切换到记录tab时加载数据
watch(activeTab, (newVal) => {
  if (newVal === 'records' && props.item) {
    loadInventoryRecords()
  }
})

const handleClose = () => {
  visible.value = false
  emit('close')
}

const handleSizeChange = (size: number) => {
  recordPagination.value.limit = size
  loadInventoryRecords()
}

const handleCurrentChange = (page: number) => {
  recordPagination.value.page = page
  loadInventoryRecords()
}

const loadInventoryRecords = async () => {
  if (!props.item) return
  
  loadingRecords.value = true
  try {
    const params = {
      productId: props.item.productId,
      page: recordPagination.value.page,
      limit: recordPagination.value.limit
    }
    
    const response = await inventoryAPI.getInventoryAdjustments(params)
    
    if (response.success) {
      // 转换数据格式
      inventoryRecords.value = response.data.list.map((record: any) => ({
        id: record.id,
        date: record.createdAt,
        type: record.adjustType === 'increase' ? 'in' : record.adjustType === 'decrease' ? 'out' : 'adjust',
        amount: record.adjustQuantity,
        balance: record.afterStock,
        reason: record.reason,
        operator: record.operatorName || '未知',
        remark: record.remark || ''
      }))
      
      recordPagination.value.total = response.data.pagination.total
    } else {
      ElMessage.error(response.message || '加载库存记录失败')
    }
  } catch (error) {
    ElMessage.error('加载库存记录失败: ' + (error as Error).message)
  } finally {
    loadingRecords.value = false
  }
}

const saveAlertSettings = () => {
  ElMessage.success('预警设置保存成功')
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const getStockStatusType = (status: string) => {
  switch (status) {
    case 'sufficient': return 'success'
    case 'warning': return 'warning'
    case 'out_of_stock': return 'danger'
    default: return 'info'
  }
}

const getStockStatusText = (status: string) => {
  switch (status) {
    case 'sufficient': return '充足'
    case 'warning': return '预警'
    case 'out_of_stock': return '缺货'
    default: return '未知'
  }
}

const getRecordType = (type: string) => {
  switch (type) {
    case 'in': return 'success'
    case 'out': return 'danger'
    case 'adjust': return 'warning'
    default: return 'info'
  }
}

const getRecordTypeText = (type: string) => {
  switch (type) {
    case 'in': return '入库'
    case 'out': return '出库'
    case 'adjust': return '调整'
    default: return '其他'
  }
}

const getAmountClass = (amount: number) => {
  if (amount > 0) {
    return 'amount-in'
  } else if (amount < 0) {
    return 'amount-out'
  }
  return ''
}
</script>

<style scoped>
.inventory-detail-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.inventory-detail {
  padding: 20px 0;
}

.alert-info {
  margin-bottom: 20px;
}

.alert-form {
  max-width: 500px;
}

.unit {
  margin-left: 8px;
  color: var(--el-text-color-secondary);
}

.amount-in {
  color: #67c23a;
}

.amount-out {
  color: #f56c6c;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 标签悬停效果 */
.status-tag,
.record-type-tag {
  transition: all 0.3s cubic-bezier(0.4, 0.6, 0.2, 1);
}

.status-tag:hover,
.record-type-tag:hover {
  transform: scale(1.05);
}

/* 标签页样式 */
.detail-tabs {
  border-radius: 4px;
}

.tab-pane {
  padding: 20px 0;
}

.detail-descriptions {
  margin-bottom: 20px;
}

.records-table {
  margin-bottom: 20px;
}

/* 表单元素悬停效果 */
.checkbox-item,
.threshold-input,
.frequency-select {
  transition: all 0.3s ease;
}

.checkbox-item:hover {
  transform: scale(1.02);
}

.threshold-input:hover,
.frequency-select:hover {
  transform: translateY(-1px);
}

/* 按钮悬停效果 */
.save-alert-btn {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.save-alert-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.save-alert-btn:active {
  transform: translateY(0);
}

.save-alert-btn::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: width 0.6s, height 0.6s;
}

.save-alert-btn:active::after {
  width: 300px;
  height: 300px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .inventory-detail-dialog {
    width: 95% !important;
  }
  
  .detail-descriptions :deep(.el-descriptions__label) {
    width: auto !important;
  }
  
  .records-table :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }
}
</style>